
package com.bang.daybreak.common.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 * 通用填充类，把公共字段填充，需要在实体类中注明。
 * </p>
 *
 * @author wdj
 * @since 2019-05-05
 */
public class CommonMetaObjectHandler implements MetaObjectHandler {

    /**
     * 创建时间
     */
    private final String createTime = "createTime";
    /**
     * 修改时间
     */
    private final String updateTime = "updateTime";
    /**
     * 创建者ID
     */
    private final String createUid = "createUser";

    /**
     * 修改者ID
     */
    private final String updateUid = "updateUser";

    @Override
    public void insertFill(MetaObject metaObject) {
        setInsertFieldValByName(createTime, LocalDateTime.now(), metaObject);
        setInsertFieldValByName(createUid, currentUid(), metaObject);
        setInsertFieldValByName(updateTime, LocalDateTime.now(), metaObject);
        setInsertFieldValByName(updateUid, currentUid(), metaObject);

        /**
         * book demo中测试自动填充器
         */
        setInsertFieldValByName("createtime", new Date(), metaObject);
        setInsertFieldValByName("uptime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setUpdateFieldValByName(updateTime, LocalDateTime.now(), metaObject);
        setUpdateFieldValByName(updateUid, currentUid(), metaObject);
        /**
         * book demo中测试自动填充器
         */
        setUpdateFieldValByName("uptime", new Date(), metaObject);
    }

    /**
     * 获取当前用户ID
     */
    private String currentUid() {
        String uid = null;
        try {
            HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
          /*  User user = (User) session.getAttribute(LogConstant.USER);
            uid = user.getAccount();*/
        } catch (Exception ignored) {
        }
        return uid;
    }

}
